package com.kaifamiao.month04.day27;

import lombok.Data;

import java.io.*;
import java.nio.file.NoSuchFileException;

//@Data
public class CutThread extends Thread {

    private final File original; // 切割的原文件
    private final File directory; // 切割之后存放的路径
    private final long start; // 当前进程开始切割的位置
    private final long size; // 单次切割的大小
    private long aLong; // 当前进程切割的总大小

    public CutThread(String name, File original, File directory, long start, long size, long aLong) {
        super(name);
        this.original = original;
        this.directory = directory;
        this.start = start;
        this.size = size;
        this.aLong = aLong;
    }

    @Override
    public void run() {

        System.out.println(this.getName() + "启动了");
        try {
            if (!original.exists() || !original.isFile()) { // 判断原文件是否存在
                throw new NoSuchFileException("文件不存在！");
            }
            if (!directory.exists()) { // 目标文件夹不存在，创建路径
                boolean flag = directory.mkdirs();
                if (!flag) {
                    System.err.println("创建文件路径失败！");
                }
            }
            RandomAccessFile in = new RandomAccessFile(original,"r");
            long arrSize = size;
            while (arrSize > Integer.MAX_VALUE) {
                arrSize = arrSize >> 1;
            }
            byte[] bytes = new byte[(int)arrSize];
            in.seek(start);
            FileOutputStream out = null;
            int len;
            String str; // 输出之后文件的路径
            long s = 0; // 单次的文件大小
            while ((len = in.read(bytes))!= -1) {
               if (aLong - size >= 0) {
                   if (s == 0) { // 第一次写
                       str = directory.getAbsolutePath() + "\\" + this.getName() + System.nanoTime() + ".temp";
                       out = new FileOutputStream(str , true);
                   }
                   out.write(bytes, 0 , len);
                   s += len;
                   aLong -= s;
                   if (s >= size) {
                       s = 0;
                   }
               } else { // 最后一次写文件
                   out.write(bytes, 0, (int)aLong);
                   out.close();
                   break;
               }
            }
            in.close();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
